<style>
    #num_rules {list-style:none;margin:0;padding:0;}
    #num_rules label{cursor:pointer;}
    #num_rules li{color:#999;padding:3px 0;background:#EFEFEF;}
    #num_rules li.active{color:#000;background:#FFc;}
</style>

<form method="POST" action="index.php?app=ome&ctl=admin_crm_gift&act=save_rule" class="" id="form_member_lv">

    <{input type="hidden" name="id" value=$rule.id }>

    <h3 class="head-title">促销规则</h3>
    <{include file='admin/gift/rule_edit1.html' app="ome" }>

    <h3 class="head-title">促销条件</h3>
    <{include file='admin/gift/rule_edit2.html' app="ome" }>

    <h3 class="head-title">赠送商品</h3>
    <{include file='admin/gift/rule_edit3.html' app="ome" }>

</form>

<div id="form_preview" style="display:none;padding:5px;">
    <h3 align="center">规则预览</h3>
    <div  class="division" style="padding:10px;line-height:2em;">
        <table>
            <col width="20%" align="right" />
            <col width="80%" align="left" />
            <tr>
                <th>活动名称：</th><td><b id="pre_title"><!--2014年父亲节赠送贺卡--></b></td>
            </tr>
            <tr>
                <th>有 效 期：</th><td>
                <b id="pre_time_type"></b> -
                <b id="pre_start_time"><!--2014-06-21--></b>  至  <b id="pre_end_time"><!--2014-06-28--></b>
            </td>
            </tr>
            <tr>
                <th>赠送规则：</th><td>
                <div id="pre_rules" style="border-radius:6px;padding:5px;background:#FFF7B2;">

                </div>
            </td>
            </tr>
            <tr>
                <th>赠送商品：</th><td><div id="pre_gifts" style="border-radius:6px;margin:2px 0 0 0;padding:5px;background:#DBE2ED;"><!--6023Y0098|上海商派ShopEx KPI 企业版 使用权1年--></div></td>
            </tr>
        </table>
    </div>
</div>

<div class="table-action">
    <{button type="button" label="保存" id="rule_preview" style="display:none;"}>

    <{button type="button" label="确认保存" id="rule_save" style="display:;"}>
    <{button type="button" label="返回" onclick="history.back();" }>

    <{button type="button" label="返回修改" id="rule_edit" style="display:none;"}>
</div>

<script>
    var status = <{$rule.status}>;
    var num_rule = '<{$rule.filter_arr.buy_goods.num_rule}>';
    var count_type = '<{$rule.filter_arr.buy_goods.count_type}>';
    var gift_template = '';//赠品列表tr模板

    (function(){

        init_select_value();

        if(!num_rule){
            num_rule = 'fixed';
        }
        var num_rule_radio = $$('#num_rules input[type=radio][value="'+num_rule+'"]');
        num_rule_radio.set('checked', 'checked');
        num_rule_radio.getParent().set('class', 'active');

        gift_template = $('gift_list').getElement('tbody').getFirst().get('html');
        $('gift_list').getElement('tbody').getFirst().remove();

        $$('input[name="status"][value='+status+']').set('checked','checked');

        //保存规则
        $('rule_save').addEvent('click', function(){
            if(chk_form() == false) return false;
            $('form_member_lv').fireEvent('submit',{stop:$empty});
        });

        //返回修改按钮
        $('rule_edit').addEvent('click', function(){
            $('form_member_lv').show();
            $('form_preview').hide();

            $('rule_preview').show();
            $('rule_save').hide();
            $('rule_edit').hide();
        });

        //订单金额类型
        $$('select[name="filter_arr[order_amount][type]"]').addEvent('change', function(){
            var ele = $(this);
            if(ele.value=='0'){
                ele.getNext().hide();
            }else{
                ele.getNext().show();
            }
        });

        $$('select[name="filter_arr[order_amount][sign]"]').addEvent('change', function(){
            var ele = $(this);
            if(ele.value=='bthan'){
                ele.getNext().hide();
            }else{
                ele.getNext().show();
            }
        });

        $$('#num_rules_sign').addEvent('change', function(){
            var ele = $(this);
            if(ele.value!='between'){
                ele.getNext().getNext().hide();
            }else{
                ele.getNext().getNext().show();
            }
        });

        $('filter_arr[buy_goods][limit_type]').addEvent('change', function(){
            var ele = $(this);
            if(ele.value=='0'){
                ele.getNext().hide();
            }else{
                if($('buy_goods_limit_orders').get('value')==''){
                    $('buy_goods_limit_orders').set('value', 10);
                }
                ele.getNext().show();
            }
        });

        $('filter_arr[buy_goods][type]').addEvent('change', function(){
            var ele = $(this);
            if(ele.value=='0'){
                ele.getNext().hide();
            }else{
                ele.getNext().show();
            }
        });

        //选项卡效果
        var tab_container = $$('#form_member_lv');
        for(var i=0;i<tab_container.length;i++){
            tab_div = tab_container[i].getElements('div');
            tab_nav = tab_div[0].getElements('li');
            tab_nav.each(function($obj,i){
                $obj.onclick=function(){
                    tab_nav.set('class','tab');
                    tab_div.setStyle('display', 'none');
                    this.set('class','tab current');
                    tab_div[0].setStyle('display', 'block');
                    tab_div[i+1].setStyle('display', 'block');
                };
            });
        }

        var _form = $('form_member_lv');
        var btn =$('rule_preview');
        var finder = finderGroup['<{$env.get.finder_id}>'];

        _form.store('target',{
            onSuccess:function(response){
                var hash_res_obj = JSON.decode(response);

                if (hash_res_obj.success != undefined && hash_res_obj.success != "")
                {
                    try{
                        var _dialogIns = btn.getParent('.dialog').retrieve('instance');
                    }catch(e){}

                    if(_dialogIns)
                    {
                        _dialogIns.close();
                        window.finderGroup['<{$env.get.finder_id}>'].refresh();
                    }
                }
            }
        });

        $('giftFilterBtn').addEvent('click',function(){
            ajax_get_gifts();
        });

        $$('#num_rules input[type=radio]').addEvent('click', function(){
            $$('#num_rules li').set('class', '');
            $(this).getParent().set('class', 'active');
        });

        $('count_type').addEvent('change', function(){
            $('count_type2').set('value', $(this).get('value'));
        });

        $('count_type2').addEvent('change', function(){
            $('count_type').set('value', $(this).get('value'));
        });

        $('addgoodsbninput').addEvent('click', function(){
            var inputs = new Element('input[type=text]',{
                'name':'filter_arr[buy_goods][goods_bn][]',
                'class':'x-input',
                'autocomplete':'off',
                'size':'15',
                'style':'margin-right:9px'
            });
            $('anchors').appendChild(inputs);
        });

    })();

    // 赠品数量控制
    function chk_num(obj){
        if(obj.value <= 0 || obj.value == ''){
            alert('赠品数必须大于0');
            obj.value = 1;
            return false;
        }
    }

    function ajax_get_gifts(){

        //清除所有未选择的赠品
        //只移除未选择的商品
        var sel_goods = '0';
        var chkBox = $$('#gift_list input[type="checkbox"]');
        chkBox.each(function($obj,i){
            var tr_obj = $obj.parentNode.parentNode;
            if($obj.get('checked') == false) {
                tr_obj.remove();
            }else{
                sel_goods += ','+$obj.value;
            }
        });

        var _url = 'index.php?app=ome&ctl=admin_crm_list&act=ajax_get_gifts';
        var _data = 'sel_goods='+sel_goods+'&s_gift_bn='+$('s_gift_bn').value+'&s_gift_name='+$('s_gift_name').value;
        new Request({
            url : _url,
            method : 'post',
            data : _data,
            onSuccess : function(responseText){
                var obj = JSON.decode(responseText);
                var gift_list = $('gift_list').getElement('tbody');
                var new_node;
                var gift_no = $$('#gift_list tbody tr').length;
                for(var i=0;i<obj.length;i++){
                    gift_no++;
                    new_node = gift_template.replace(/<!--gift_id--\>/g,obj[i].gift_id).replace('<!--gift_name--\>',obj[i].gift_name.substring(0,22)).replace('<!--gift_bn--\>',obj[i].gift_bn).replace('<!--gift_no--\>',gift_no);
                    var new_tr = new Element('tr');
                    new_tr.set('html',new_node);
                    new_tr.inject(gift_list);
                }
            }
        }).send();
    }

    function get_selected_text(ele){
        return ele.options[ele.selectedIndex].text;
    }

    //规则预览
    function rule_preview(){

        if(chk_form()==false){
            return false;
        }

        var _form = $('form_member_lv');

        $('pre_title').set('text', _form.getElement('input[name="title"]').value);
        $('pre_time_type').set('text', get_selected_text($('time_type')));
        $('pre_start_time').set('text', _form.getElement('input[name="start_time"]').value);
        $('pre_end_time').set('text', _form.getElement('input[name="end_time"]').value);

        var pre_rules_html = [];
        if($('shop_id').get('value')){
            pre_rules_html.push('<b>指定店铺</b>：' + get_selected_text($('shop_id')) );
        }
        if($('lv_id').get('value') != '0'){
            pre_rules_html.push('<b>客户等级</b>：' + get_selected_text($('lv_id')) );
        }
        if($('order_amount_type').get('value') != '0'){
            var amount_limit = '';
            if($('order_amount_sign').get('value') == 'between'){
                amount_limit = $('order_amount_min_num').get('value') + '元 ~' + $('order_amount_max_num').get('value') + '元';
            }else{
                amount_limit = $('order_amount_max_num').get('value') + '元';
            }
            pre_rules_html.push('<b>订单金额</b>：' + get_selected_text($('order_amount_type')) +get_selected_text($('order_amount_sign')) + amount_limit );
        }
        if($('filter_arr[buy_goods][type]').get('value') != '0'){
            pre_rules_html.push('<b>指定商品货号</b>：' + $('goods_bn').value + '<br/>　　　　' + get_num_rules() );
        }
        $('pre_rules').set('html', pre_rules_html.join('<br/>'));

        //限定：指定购买商品
        if($('filter_arr[buy_goods][type]').get('value') == 1){
            //$('pre_buy_goods').set('html', '<font color=blue>'+$('goods_name').get('html')+'</font> 大于<font color=red>'+$('buy_goods_min_num').get('value')+'</font>件');
        }else{
            //$('pre_buy_goods').set('html', '-');
        }

        //内容切换
        $('form_member_lv').hide();
        $('form_preview').show();

        //按钮切换
        $('rule_preview').hide();
        $('rule_save').show();
        $('rule_edit').show();
    }

    //预设下拉框的值
    function init_select_value(){

        var _form = $('form_member_lv');

        _form.getElement('select[name="filter_arr[order_amount][type]"]').set('value', '<{$rule.filter_arr.order_amount.type}>');

        _form.getElement('select[name="filter_arr[order_amount][sign]"]').set('value', '<{$rule.filter_arr.order_amount.sign}>');

        _form.getElement('select[name="filter_arr[buy_goods][rules_sign]"]').set('value', '<{$rule.filter_arr.buy_goods.rules_sign}>');

        _form.getElement('select[name="filter_arr[buy_goods][type]"]').set('value', '<{$rule.filter_arr.buy_goods.type}>');

        _form.getElement('select[name="filter_arr[buy_goods][buy_type]"]').set('value', '<{$rule.filter_arr.buy_goods.buy_type}>');

        _form.getElement('select[name="filter_arr[buy_goods][limit_type]"]').set('value', '<{$rule.filter_arr.buy_goods.limit_type}>');

        _form.getElement('select[name="filter_arr[buy_goods][count_type]"]').set('value', '<{$rule.filter_arr.buy_goods.count_type}>');

        _form.getElement('select[name="filter_arr[buy_goods][count_type2]"]').set('value', '<{$rule.filter_arr.buy_goods.count_type}>');
    }

    //检测必填项
    function chk_form(){
        var _form = $('form_member_lv');

        if($('title').get('value')==''){
            alert('请输入规则名称');
            $('title').focus();
            return false;
        }

        if($('time_type').get('value')==''){
            alert('请选择时间类型');
            $('time_type').focus();
            return false;
        }

        if($('start_time').get('value')==''){
            alert('请输入生效时间');
            $('start_time').focus();
            return false;
        }

        if($('end_time').get('value')==''){
            alert('请输入结束时间');
            $('end_time').focus();
            return false;
        }

        //限定：购买金额
        var order_amount_type = get_selected_text($('order_amount_type'));

        if(order_amount_type != '无限制'){
            var order_amount_sign = get_selected_text($('order_amount_sign'))
            var order_amount_min_num = $('order_amount_min_num').get('value');
            var order_amount_max_num = $('order_amount_max_num').get('value');

            if(chk_money(order_amount_max_num) == false){
                alert('请输入最高金额');
                return false;
            }

            if(order_amount_sign == '介于'){
                if(chk_money(order_amount_min_num) == false){
                    alert('请输入最低金额');
                    return false;
                }
            }
        }

        if($('filter_arr[buy_goods][type]').get('value')==1){
            var goods_bn = $$('input[name="filter_arr[buy_goods][goods_bn][]"]').get('value');
            var goods_bns = '';
            goods_bn.each(function(v){
                goods_bns += v.trim();
            });
            if(goods_bns === ''){
                alert('请至少输入一个商品货号');
                return false;
            }
        }

        if($('filter_arr[buy_goods][limit_type]').get('value') == 1){
            if(chk_int($('buy_goods_limit_orders').value) == false){
                alert('限量赠送 请输入送出赠品的最多订单数量');
                $('buy_goods_limit_orders').focus();
                return false;
            }
        }

        if(chk_num_rules() == false){
            return false;
        }
        //赠品列表预览
        var gift_list = [];
        $$('#gift_list input:checked').each(function(ele){
            gift_list.push(ele.getParent().getNext().getNext().getNext().get('text') + '　x　<b><font color=red>' + ele.getParent().getParent().getElement('input[type="text"]').value + '</font></b> 件');
        });
        if(gift_list.length == 0){
            alert('请选择至少一个赠送商品');
            return false;
        }
        $('pre_gifts').set('html', gift_list.join(';<br/>'));

        return true;
    }

    function get_num_rules(){
        var num_rule = $$('#num_rules input[type=radio]:checked').get('value');
        var str = '';

        if(num_rule == 'fixed'){
            if($('num_rules_sign').get('value')=='between'){
                str = '购买数量' + get_selected_text($('num_rules_sign')) + $('buy_goods_min_num').value + '~' + $('buy_goods_max_num').value;
            }else{
                str = '购买数量' + get_selected_text($('num_rules_sign')) + $('buy_goods_min_num').value;
            }
        }else if(num_rule == 'limit_orders'){
            str = '购买此商品的前 '+ $('buy_goods_limit_orders').value +' 笔订单赠送1组赠品';
        }else if(num_rule == 'auto'){
            str = '每购买 '+$('per_num').value+' 件， 赠送 '+$('send_suite').value+' 组赠品， 每订单最多送 '+ $('max_send_suite').value +' 组';
        }

        return str;
    }

    function chk_num_rules(){
        var num_rule = $$('#num_rules input[type=radio]:checked').get('value');
        //alert('='+num_rule+'=')

        if(num_rule == 'fixed'){
            if(chk_int($('buy_goods_min_num').value) == false){
                alert('促销条件 请输入最小购买数量');
                return false;
            }
            if($('num_rules_sign').get('value')=='between' && chk_int($('buy_goods_max_num').value) == false){
                alert('促销条件 请输入最大购买数量');
                return false;
            }
        }else if(num_rule == 'limit_orders'){
            if(chk_int($('buy_goods_limit_orders').value) == false){
                alert('促销条件 请输入限定订单数');
                return false;
            }
        }else if(num_rule == 'auto'){
            if(chk_int($('per_num').value) == false){
                alert('促销条件 请输入订单数');
                return false;
            }
            if(chk_int($('send_suite').value) == false){
                alert('促销条件 请输入赠送套数');
                return false;
            }
            if(chk_int($('max_send_suite').value) == false){
                alert('促销条件 请输入总赠送套数');
                return false;
            }
        }
    }

    //设置背景色
    function set_bg_color(e){
        if(e.checked === true){
            e.getParent().getParent().style.backgroundColor = '#FFFFCC';
        }else{
            e.getParent().getParent().style.backgroundColor = '';
        }
    }

    function chk_int(val){
        var reg = new RegExp("^([1-9]+)([0-9]*)$");
        if(!reg.test(val)){
            return false;
        }
    }

    function chk_money(val){
        var reg = new RegExp("^([0-9]+)(\.*)([0-9]*)$");
        if(!reg.test(val)){
            return false;
        }
    }
</script>
